package client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import actions.Commands;


public class Cliente {
	
	static final String HOST = "localhost";
	final int puerto;
	
	PrintWriter out;
	BufferedReader in;
	
	Socket serverSocket;
	
	final String user;
	final String chatServerName;
	
	public Cliente( String _user, int _puerto, String _chatServer ) 
	{
		user=_user;
		puerto=_puerto;
		chatServerName=_chatServer;
	}

	public void haltServer() {
		try
		{
			initConnection();
					
			
			out.println("halt");
			
		} 
		catch( Exception e ) 
		{
			System.out.println( e.getMessage() );
		}
		finally
		{
			closeConnection();

		}
	}
	
	public void register() {
		try
		{
			initConnection();
			
			out.println("#"+Commands.REGISTER+" "+user);
			
			System.out.println(in.readLine());
							
		} 
		catch( Exception e ) 
		{
			System.out.println( e.getMessage() );
		}
		finally
		{
			closeConnection();

		}
	}
	public void unRegister() {
		try
		{
			initConnection();
			
			out.println("#"+Commands.UNREGISTER+" "+user);
			
			System.out.println(in.readLine());
							
		} 
		catch( Exception e ) 
		{
			System.out.println( e.getMessage() );
		}
		finally
		{
			closeConnection();

		}
	}
	public void sendMsj(String _msj) {
		try
		{
			initConnection();
			
			out.println("#"+Commands.ADD+" "+user+" "+_msj);
			System.out.println(in.readLine());
							
		} 
		catch( Exception e ) 
		{
			System.out.println( e.getMessage() );
		}
		finally
		{
			closeConnection();

		}
	}



	private void closeConnection() {
		try
		{
			serverSocket.close();
			out.close();
			in.close();
		}
		catch (Exception e)
		{
		}
	}

	private void initConnection() throws UnknownHostException, IOException {
		serverSocket = new Socket( HOST , puerto );
		
		out = new PrintWriter(serverSocket.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
		
		out.println(user);
	}
	


}


